from typing import TypeVar, Generic, List, Dict, Any
from sqlalchemy.orm import Query
from math import ceil

T = TypeVar('T')

class PaginatedResult(Generic[T]):
    def __init__(
        self,
        items: List[T],
        page: int,
        per_page: int,
        total: int
    ):
        self.items = items
        self.page = page
        self.per_page = per_page
        self.total = total
        self.pages = ceil(total / per_page)

    def to_dict(self) -> Dict[str, Any]:
        return {
            'items': [item.to_dict() for item in self.items],
            'page': self.page,
            'per_page': self.per_page,
            'total': self.total,
            'pages': self.pages,
            'has_next': self.has_next,
            'has_prev': self.has_prev
        }

    @property
    def has_next(self) -> bool:
        return self.page < self.pages

    @property
    def has_prev(self) -> bool:
        return self.page > 1

def paginate(query: Query, page: int = 1, per_page: int = 20) -> PaginatedResult:
    """分页查询"""
    items = query.limit(per_page).offset((page - 1) * per_page).all()
    total = query.order_by(None).count()
    return PaginatedResult(items, page, per_page, total) 